<template>
  <view>
    <view class=" main-box">
      <view class="flex align-center justify-between house-box">
        <view>
          <view class="title">{{ confirmationData.housingAllocation.apartmentDescription }}</view>
          <view class="tip-title">{{ confirmationData.housingAllocation.title }}</view>
        </view>
        <image class="home-img" :src="confirmationData.housingAllocation.apartmentPicture[0]" mode="aspectFill">
        </image>
      </view>
      <u-line></u-line>
      <view class="flex justify-between" style="margin-top: 30rpx;" @tap="selectDate">
        <view class="left-time">
          {{ form.startTime|formatDate('MM月dd日 w') }}-{{ form.endTime|formatDate('MM月dd日 w') }}
        </view>
        <view class="flex align-center right-subday">
          <text
              style="margin-right: 20rpx;">共{{ subDay }}晚
          </text>
          <u-icon size="11" name="arrow-right"></u-icon>
        </view>
      </view>
    </view>
    <view class="check-info main-box" style="margin-top: 30rpx;">
      <view class="flex justify-between">
        <text class="main-title">入住信息</text>
        <text class="right-person">
          {{ roomPerson }}/{{ confirmationData.house ? confirmationData.house.checkInNumber : 0 }}
        </text>
      </view>
      <view class="flex justify-between align-center" style="margin-top: 30rpx;" v-if="lessee.personId!=''">
        <view>
          <view class="flex align-center">
            <text class="person-name">{{ lessee.personName }}</text>
            <view class="lessee-tag">承租人</view>
          </view>
          <view class="tip-text">手机号：{{ lessee.personPhone }}</view>
          <view class="tip-text">身份证：{{ lessee.idCard }}</view>
        </view>
        <view>
          <image class="del-img" @click="removeLessee"
                 src="https://saas-v5.oss-cn-guangzhou.aliyuncs.com/saas-admin/druid/mpimg/person-del.png"
                 mode=""></image>
        </view>
      </view>
      <view class="flex justify-between align-center" style="margin-top: 30rpx;"
            v-for="(item,index) in personList" :key="index">
        <view>
          <view class="flex">
            <text style="margin-right: 20rpx;">{{ item.personName }}</text>
            <view class="person-tag">同住人</view>
          </view>
          <view class="tip-text">手机号：{{ item.personPhone }}</view>
          <view class="tip-text">身份证：{{ item.idCard }}</view>
        </view>
        <view>
          <image class="del-img" @click="removePerson(index)"
                 src="https://saas-v5.oss-cn-guangzhou.aliyuncs.com/saas-admin/druid/mpimg/person-del.png"
                 mode=""></image>
        </view>
      </view>
      <view class="add-text"
            v-if="lessee.personId==''&&roomPerson<confirmationData.house.checkInNumber"
            @click="addLessee">添加承租人
      </view>
      <view class="add-text"
            v-if="lessee.personId!=''&&roomPerson<confirmationData.house.checkInNumber"
            @click="addRoommate">添加同住人
      </view>
    </view>
    <view class="main-box" style="margin-top: 30rpx;">
      <view class="main-title">账单信息</view>
      <view class="price-box">
        <view class="item-price" v-for="(item,index) in priceData.orderChargeItemList" :key="index">
          <view class="flex justify-between">
            <view class="price-title">{{ item.chargeType == '1' ? '房费' : '押金' }}
              <text class="subday" v-if="item.chargeType=='1'">(共{{ item.purchaseQuantity }}晚)</text>
            </view>
            <view class="price-num">￥{{ item.itemSum }}</view>
          </view>
          <view class="tip-price" v-if="item.chargeType=='2'">下单时同时收取，离店后退还</view>
        </view>
        <view class="coupon-box">
          <view class="flex justify-between">
            <view class="coupon-label">优惠券
            </view>
            <view class="coupon-more" @click.stop="handleShowCoupon">
              <view class="flex align-center">
                <view class="coupon-price" v-if="couponRecordList.length>0">-￥{{ priceData.couponPrice }}</view>
                <view v-else>{{ couponList.length }}张可用</view>
                <u-icon name="arrow-right"></u-icon>
              </view>

            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="bottom-box flex justify-between align-center">
      <text class="money flex align-end">
        <text class="money-icon">￥</text>
        {{ priceData.totalPrice < 0 ? 0 : priceData.totalPrice }}
      </text>
      <button class="submit-btn" @click="submitOrder">提交订单</button>
    </view>
    <u-popup :show="show" round="20" @close="close" @open="open" :closeable="true">
      <person-tep v-if="show" :lesseeId="lessee.personId" :type="addPersonType" :length="roomPerson"
                  :maxLength="confirmationData.house.checkInNumber" :personIdList="personIdList"
                  @submit="personSubmit"></person-tep>
    </u-popup>
    <!-- 日历组件 -->
    <uvCalendar :show="showCalendar" :priceList="priceList" :formatter="formatter" mode="range"
                @close="closeCalendar" @confirm="confirmCalendar" color="#FF7947" startText="入住时间"
                endText="离开时间"
                monthNum="12" :default-date="defaultDate" ref="calendar">
    </uvCalendar>
    <!-- 优惠券组件 -->
    <u-popup :show="showCoupon" @close="showCoupon = false" round="20" :closeable="true" @touchmove.prevent>
      <coupon v-if="showCoupon" :params="couponUseableParams" :selectedCoupon="couponRecordList" @submit="couponSubmit"
              @close="showCoupon = false"></coupon>
    </u-popup>
  </view>
</template>

<script>
// import personTep from "@/components/person/list.vue";
import personTep from "./components/person/index.vue"
import uvCalendar from '@/components/uv-calendar/uv-calendar.vue';
import coupon from "./components/coupon/index.vue"
import {
  confirmation,
  placeOrder,
  compute,
  getPriceList
} from '@/api/home';
import {
  DateDiff,
  dateToFormat,
  DateAdd,
  formatCnDate
} from '@/utils/time.js'
import {getCouponByHouseIdUseState} from "@/api/mine/coupon";

export default {
  data() {
    return {
      priceList: [],
      showCalendar: false,
      defaultDate: [],
      addPersonType: 'lessee', //lessee承租
      show: false,
      confirmationData: {},
      houseId: '',
      userInfo: this.$store.state.user.userInfo,
      lessee: {
        personId: ''
      }, //承租人
      form: {
        "orderId": "", //订单id
        "startTime": "", //开始时间
        "endTime": "", //结束时间
        "openId": this.$store.state.user.userInfo.openId, //用户openId
        "lesseeId": '', //承租人id
        "memberIdList": [] //同住人id集合
      },
      personList: [],
      priceData: {},
      // 优惠券列表
      couponList: [],
      // 是否显示优惠券弹窗
      showCoupon: false,
      //可用/不可用优惠券参数
      couponUseableParams: {
        houseId: '',
        useState: '0', //优惠券使用状态(0:可使用,1:不可使用)
        couponThreshold: null,
      },
      couponRecordList: [], //使用过的优惠券集合
    }
  },
  computed: {
    subDay: {
      get() {
        return (this.form.startTime && this.form.endTime) ? DateDiff(this.form.startTime, this.form.endTime) : 0;
      },
      set() {

      }

    },
    personIdList: {
      get() {
        let ids = this.personList.map(item => item.personId);
        if (this.lessee.personId) {
          ids.push(this.lessee.personId)
        }
        return ids
      }
    },
    roomPerson: {
      get() {
        if (this.lessee.personId == '') {
          return this.personList.length ? this.personList.length : 0
        } else {
          return this.personList.length + 1
        }

      },
    }
  },
  components: {
    personTep,
    uvCalendar,
    coupon
  },
  onReady() {
    // 如果需要兼容微信小程序的话，需要用此写法
    this.$refs.calendar.setFormatter(this.formatter)
  },
  onLoad(options) {
    this.houseId = options.houseId;
    this.form.startTime = options.startTime;
    this.form.endTime = options.endTime;
    this.getData();
    this.form.openId = this.userInfo.openid;
  },
  methods: {
    selectDate() {
      let longtime;
      switch (this.confirmationData.housingAllocation.leaseScope) {
        case '1':
          longtime = 3
          break;
        case '2':
          longtime = 6
          break;
        case '3':
          longtime = 12
          break;
        case '4':
          longtime = 24
          break;
        default:
          break;
      }
      let date = new Date();
      let startTime = formatCnDate(date, 'yyyy-MM-dd hh:mm:ss')
      let endTime = date.setMonth(date.getMonth() + longtime) - (60 * 60 * 24 * 1000);

      let data = {
        "startTime": startTime, //开始时间
        "endTime": formatCnDate(endTime, 'yyyy-MM-dd hh:mm:ss'), //结束时间
        "houseId": this.houseId //房屋id
      }
      getPriceList(data).then(res => {
        this.priceList = res.data;
        this.showCalendar = true;
      })
    },
    formatter(day, priceList) {
      const d = new Date()
      let month = d.getMonth() + 1
      const date = d.getDate()
      let time = priceList.find(item => {
        return item.calendarTime == formatCnDate(day.date)
      })
      if (time && time.reserveState == 0) {
        day.bottomInfo = '￥' + time.calendarPrice
      } else if (time && time.reserveState == 1) {
        day.bottomInfo = '无房'
      }
      return day
    },
    removeLessee() {
      this.lessee = this.$options.data().lessee;
    },
    removePerson(index) {
      this.personList.splice(index, 1)
    },
    closeCalendar() {
      this.showCalendar = false
    },
    confirmCalendar(e) {
      this.form.startTime = e[0] + ' 00:00:00';
      this.form.endTime = e[e.length - 1] + ' 00:00:00';
      let subDay = DateDiff(e[0], e[e.length - 1])
      this.subDay = subDay
      this.showCalendar = false
      this.computePrice();
    },
    computePrice() {
      let data = {
        houseId: this.houseId,
        orderId: this.confirmationData.orderId,
        startTime: this.form.startTime,
        endTime: this.form.endTime,
        couponRecordIdList: this.couponRecordList.map(item => item.couponRecordId),
      }
      compute(data).then(res => {
        this.priceData = res.data;
        console.log('priceData', this.priceData)
        this.couponUseableParams.houseId = this.houseId
        this.couponUseableParams.couponThreshold = res.data.orderChargeItemList.find(item => item.chargeType === '1').itemSum
        this.getUseableCoupon();
      })
    },
    addLessee() {
      this.addPersonType = 'lessee';
      this.show = true;

    },
    addRoommate() {
      this.addPersonType = 'roommate';
      this.show = true;
    },
    personSubmit(row) {
      if (this.addPersonType == 'lessee') {
        this.lessee = row[0];
      } else {
        this.personList = this.personList.concat(row)
      }
      this.close();
    },
    // 获取可用优惠券
    getUseableCoupon() {
      let params = this.couponUseableParams;
      getCouponByHouseIdUseState(params).then(res => {
        console.log('useableCoupon', res.rows)
        this.couponList = res.rows;
      })
    },
    // 显示优惠券弹窗
    handleShowCoupon() {
      this.showCoupon = true;
    },
    // 优惠券弹窗提交
    couponSubmit(data) {
      console.log('data', data)
      this.couponRecordList = data
      this.computePrice();
    },
    getData() {
      confirmation(this.houseId).then(res => {
        let data = res.data;
        data.housingAllocation.apartmentPicture = data.housingAllocation.apartmentPicture.split(',')
        this.confirmationData = data;
        this.form.orderId = res.data.orderId;
        this.computePrice();
      })
    },
    close() {
      this.show = false;
    },
    open() {

    },
    toAddMan() {
      this.show = true;
      // uni.navigateTo({
      // 	url: '/pages/main/checkMan/list'
      // })
    },
    submitOrder() {
      if (this.lessee.lesseeId == '') {
        uni.showToast({
          title: '请添加承租人'
        })
        return
      }
      this.form.lesseeId = this.lessee.personId;
      this.form.memberIdList = this.personList.map(item => item.personId);
      let form = this.form;
      form['couponRecordIdList'] = this.couponRecordList.map(item => item.couponRecordId);
      console.log(this.form);
      let that = this;
      placeOrder(form).then(res => {
        let option = res.data;
        wx.requestPayment({
          timeStamp: option.timeStamp + "",
          nonceStr: option.nonceStr,
          package: option.package,
          signType: 'MD5',
          paySign: option.paySign,
          success(success) {
            uni.showToast({
              title: '支付成功',
              icon: 'success',
            })
            setTimeout(() => {
              uni.hideLoading()
              uni.redirectTo({
                url: '/pages/main/order/paySuccess?orderId=' + that.form.orderId
              })
            }, 1000)

          },
          fail(err) {
            console.log('err', that.form);
            uni.showToast({
              title: '你已取消支付！',
              icon: 'none',
            })
            setTimeout(() => {
              uni.hideLoading()
              uni.redirectTo({
                url: '/pages/main/order/orderDetail?orderId=' + that.form.orderId
              })
            }, 1000)
          }
        })

      })

    },
  }
}
</script>

<style>
page {
  padding: 20rpx 30rpx;
}
</style>
<style lang="scss">
.main-title {

  font-weight: 800;
  font-size: 36rpx;
  color: #000000;

}

.main-box {
  width: 690rpx;
  padding: 20rpx 32rpx;
  background-color: #fff;
  border-radius: 20rpx;
}


.check-info {
  width: 690rpx;
  padding: 20rpx 30rpx;
  background-color: #fff;

  .right-person {

    font-weight: bold;
    font-size: 30rpx;
    color: #000000;
    text-align: right;
  }

}

.add-text {
  color: #00adf0;
  text-align: center;
  margin-top: 30rpx;
}

.tip-text {
  font-weight: 500;
  font-size: 24rpx;
  color: #666666;
  margin-top: 8rpx;
}

.bottom-box {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 750rpx;
  height: 100rpx;
  background: #FFFFFF;
  box-sizing: content-box;
  box-shadow: 0rpx -2rpx 0rpx 2rpx rgba(112, 112, 112, 0.16);
  border-radius: 0rpx 0rpx 0rpx 0rpx;
  padding-bottom: constant(safe-area-inset-bottom); // 兼容 IOS<11.2
  padding-bottom: env(safe-area-inset-bottom); // 兼容 IOS>11.2

  .money {
    font-size: 36rpx;
    font-weight: 500;
    width: 74rpx;
    height: 56rpx;
    font-family: DIN, DIN;
    font-weight: bold;
    font-size: 46rpx;
    color: #FF3E27;


    margin-left: 30rpx;

    .money-icon {

      font-weight: bold;
      font-size: 26rpx;
      color: #FF3E27;


    }
  }

  .submit-btn {
    width: 196rpx;
    height: 88rpx;
    line-height: 88rpx;
    background: #FF7947;
    border-radius: 20rpx 20rpx 20rpx 20rpx;

    font-weight: 500;
    font-size: 30rpx;
    color: #FFFFFF;
    text-align: center;


    margin-left: 0;
    margin-right: 0;
    margin-right: 30rpx;
  }
}

.home-img {
  width: 132rpx;
  height: 132rpx;
  border-radius: 20rpx;
}

.house-box {
  margin-bottom: 24rpx;

  .title {
    width: 406rpx;
    font-weight: 800;
    font-size: 28rpx;
    color: #111111;
    margin-bottom: 4rpx;

    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .tip-title {
    font-weight: 400;
    font-size: 24rpx;
    color: #757575;
  }
}

.left-time {
  font-weight: 800;
  font-size: 28rpx;
  color: #000000;
}

.right-subday {
  font-weight: 500;
  font-size: 22rpx;
  color: #000000;
}

.del-img {
  width: 64rpx;
  height: 64rpx;
}

.person-name {
  font-weight: bold;
  font-size: 32rpx;
  color: #111111;


  margin-right: 14rpx;
}

.person-tag {
  width: 88rpx;
  height: 36rpx;
  background: #EEEEEE;
  border-radius: 6rpx 6rpx 6rpx 6rpx;

  font-weight: 400;
  font-size: 22rpx;
  color: #111111;
  line-height: 36rpx;
  text-align: center;


}

.lessee-tag {
  width: 88rpx;
  height: 36rpx;
  background: #FCEEE0;
  border-radius: 6rpx 6rpx 6rpx 6rpx;

  font-weight: 400;
  font-size: 22rpx;
  color: #A66237;
  line-height: 36rpx;
  text-align: center;


}

.price-box {
  view:last-child {
    border-bottom: none;
  }

  .item-price {
    border-bottom: 2rpx solid rgba(112, 112, 112, 0.1);
    padding: 46rpx 0;

    .price-num {

      font-weight: 800;
      font-size: 26rpx;
      color: #111111;


    }

    .price-title {

      font-weight: bold;
      font-size: 28rpx;
      color: #111111;


      .subday {

        font-weight: 500;
        font-size: 22rpx;
        color: #979797;


        margin-left: 6rpx;
      }

      .tip-price {

        font-weight: 500;
        font-size: 24rpx;
        color: #666666;


        margin-top: 8rpx;
      }

    }
  }

  .coupon-box {
    border-bottom: 2rpx solid rgba(112, 112, 112, 0.1);
    padding: 46rpx 0;

    .coupon-label {
      font-weight: bold;
      font-size: 28rpx;
      color: #111111;
    }

    .coupon-more {
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #666666;

      .coupon-price {
        color: #FF3E27;
      }
    }
  }
}
</style>